#!/usr/bin/python -S
"""
util.py

Random utilities that don't belong elsewhere.
"""

__author__ = 'Andy Chu'


class BlockStrError(Exception):
  """Raised when a block string has invalid syntax."""


def BlockStr(s):
  """
  A wrapper meant to be used with multiline string syntax.  This strips leading
  whitespace so you can indent strings, instead of ugly strings that are flush
  left.

  Recommendation: Use B() as an alias.
  """
  lines = s.splitlines(True)
  try:
    if lines[0] != '\n':
      raise BlockStrError('Block string must start with a newline')
  except IndexError:
    raise BlockStrError('Need at least one line')

  # Use the *last* line as the indicator for indentation (so we can have
  # blocks where every "real" line is indented)
  num_leading = len(lines[-1]) - len(lines[-1].lstrip(' '))
  if num_leading == 0:
    raise BlockStrError(
        'Second line of block string must begin with whitespace')

  del lines[-1]
  return ''.join(line[num_leading:] for line in lines)
